package com.itheima.controller;


import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController  //  二合一
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 查全部
    @GetMapping
    public Result getAll() {
        return new Result(Code.GET_OK, "查询成功",
                bookService.getAll());
    }

    // 按照id 查询
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {

        return new Result(Code.GET_OK, "查询成功",
                bookService.getById(id));
    }

    // 新增
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean b = bookService.save(book);
        return new Result(b ? Code.SAVE_OK : Code.SAVE_ERR,
                b ? "添加成功" : "添加失败", book);
    }

    // 修改
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean b = bookService.update(book);
        return new Result(b ? Code.UPDATE_OK : Code.UPDATE_ERR,
                b ? "修改成功" : "修改失败", book);
    }

    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean b = bookService.delete(id);
        return new Result(b ? Code.DELETE_OK : Code.DELETE_ERR,
                b ? "删除成功" : "删除失败",
                null);
    }


}
